import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {tap} from 'rxjs/operators';
import {Observable} from 'rxjs/index';
import {TpStorageService} from './tp-storage.service';
import {Site} from '../entity/site';

@Injectable({
    providedIn: 'root'
})
export class TpHttpService {
    constructor(private http: HttpClient, private tpStorageService: TpStorageService) {
    }

    public getHttpClient(): HttpClient {
        return this.http;
    }

    public get<T>(url: string): Observable<T> {
        const headers = this.createRequestHeader();
        const finalURI = encodeURI(url);
        console.log('get:' + finalURI + ',headers:' + JSON.stringify(headers));
        return this.http.get<T>(finalURI, {headers: headers})
            .pipe(
                tap((resp: T) => {
                    console.log(`get:${finalURI}, resp:${JSON.stringify(resp)}`);
                    this.checkResponse(resp);
                }, e => {
                    console.error(e);
                }, () => {

                })
            );
    }

    public post<T>(url: string, body: any): Observable<T> {
        const headers = this.createRequestHeader();
        const finalURI = encodeURI(url);

        console.log('post:' + finalURI + ',headers:' + JSON.stringify(headers));
        if (body && typeof body !== 'string') {
            body = JSON.stringify(body);
        }
        return this.http.post<T>(finalURI, body, {headers: headers})
            .pipe(
                tap(resp => {
                    console.log(`post:${finalURI}, resp:${JSON.stringify(resp)}`);
                    this.checkResponse(resp);
                }, e => {
                    console.error(e);
                }, () => {

                })
            );
    }

    public del<T>(url: string) {
        const headers = this.createRequestHeader();
        const finalURI = encodeURI(url);

        console.log('delete:' + finalURI + ',headers:' + JSON.stringify(headers));
        return this.http.delete<T>(finalURI, {headers: headers})
            .pipe(
                tap(resp => {
                    console.log(`delete:${finalURI}, resp:${JSON.stringify(resp)}`);
                    this.checkResponse(resp);
                }, e => {
                    console.error(e);
                }, () => {

                })
            );
    }

    public checkResponse(resp) {
        if (resp && resp.code === 401) {
            this.tpStorageService.clearUser();
        }
    }

    private createRequestHeader(): HttpHeaders {
        const tpDocToken = this.tpStorageService.get(TpStorageService.KEY_TP_DOC_TOKEN);
        return new HttpHeaders({
            'Content-Type': 'application/json;charset=utf-8',
            'domain': window.location.host,
            'auth-token': tpDocToken ? tpDocToken : ''
        });
    }
}
